<?php

	class RClassDb
	{
		var $query;
		
		var $prefix = '';
		
		function __construct($options)
		{
			$backtrace = debug_backtrace();
			if ($options === NULL)
			{
				$options['dbhost'] = RClassConfigs::$dbhost;
				$options['dbname'] = RClassConfigs::$dbname;
				$options['dbuser'] = RClassConfigs::$dbuser;
				$options['dbpass'] = RClassConfigs::$dbpass;
				$options['charset'] = RClassConfigs::$charset;
			}
			
			if (!mysql_connect($options['dbhost'], $options['dbuser'], $options['dbpassword'])
				|| !mysql_select_db($options['dbname']))
				throw new RDBException(RError::connectionFailed($options, $backtrace[1]['file'], $backtrace[1]['line']));
			if (isset($options['charset']))
				if (!mysql_query('SET CHARACTER SET '.$options['charset']))
					throw new RDBException(RError::incorrectQuery($options, $backtrace[1]['file'], $backtrace[1]['line']));
		}
		
		function getInstance($options = NULL)
		{
			static $instance;
			
			if ($instance) return $instance;
			
			$instance = new RClassDb($options);
			return $instance;
		}
		/* 
		function setQuery($query)
		{
			$this->query = $query;
		} */
		
		function getSingle($query)
		{
			$res = mysql_query($query);
			return mysql_fetch_assoc($res);
		}
		
		function getMultiple($query, $index = NULL)
		{
			$res = mysql_query($query);
			$values = array();
			if (!$index)
				while($row = mysql_fetch_assoc($res))
					$tmp[] = $row;
			else while($row = mysql_fetch_assoc($res))
					$tmp[$row[$index]][] = $row;
			return $tmp;
		}
		
		function setValues($query)
		{
			$this->setPrefix($query);
			echo $query;
			$backtrace = debug_backtrace();
			if(!mysql_query($query))
				throw new RDBException(RError::incorrectQuery($query, $backtrace[1]['file'], $backtrace[1]['line']));
		}
		
		function getError()
		{
			return mysql_error();
		}
		
		function getLastId()
		{
			return mysql_insert_id();
		}
		
		function setPrefix(& $query)
		{
			$query = str_replace('#__', $this->prefix, $query);
		}
	}
